package com.yanyu.init.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yanyu.init.constant.UserConstant;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    /**
     * 签名
     */
    private static final String SECRET = "yuan_Auth";

    /**
     * 令牌生成
     */
    public static String createToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        //过期时间
        Calendar expires = Calendar.getInstance();
        expires.add(Calendar.SECOND, UserConstant.JWT_TIMEOUT);
        //设置过期时间
        builder.withExpiresAt(expires.getTime());
        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token
     */
    public static void verifyToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * 获取token中的payload
     */
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
}
